package com.jiuxian.scheduling.rpc;

import com.jiuxian.scheduling.commons.DubboApplicationContext;
import com.jiuxian.scheduling.commons.SpringApplicationContext;
import com.jiuxian.scheduling.rpc.rpc.DubboRequestRpc;
import com.jiuxian.scheduling.rpc.rpc.HttpRequestRpc;
import com.jiuxian.scheduling.rpc.rpc.LocalRequestRpc;
import com.jiuxian.scheduling.util.ProtocolEnum;
import com.jiuxian.scheduling.util.SiteUtil;
import com.jiuxian.scheduling.vo.SchedingVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.Request;

import java.lang.reflect.Method;

/**
 * Created by wangjingqing on 2017/12/18.
 */
public class RequestRpcBuild {


    static Logger logger = LoggerFactory.getLogger(RequestRpcBuild.class);

    public static RequestRpc build(SchedingVO schedingVO){

        String protocol = schedingVO.getProtocol();
        if(ProtocolEnum.dubbo.getName().equals(protocol)){
            Object obj = DubboApplicationContext.getObject(schedingVO.getPath(),schedingVO.getUrl(),schedingVO.getVersion(),schedingVO.getGroup());
            Method method = SiteUtil.getMethod(obj, schedingVO.getMethod(),SiteUtil.getStringForJSON(schedingVO.getParameters()));
            if(method == null){
                throw new RuntimeException(obj.getClass().getName()+"中不存在"+schedingVO.getMethod()+"方法");
            }
            return new DubboRequestRpc(method,obj,schedingVO);
        }else if(ProtocolEnum.http.getName().equals(protocol)){
            HttpRequestRpc request = new HttpRequestRpc();
            request.setMethod(schedingVO.getMethod());
            request.setPath(schedingVO.getPath());
            request.setContentType(schedingVO.getGroup());
            request.setParameters(schedingVO.getParameters());
           return request;
        }else if(ProtocolEnum.local.getName().equals(protocol)){
            try {
                String name = schedingVO.getPath();
                Object obj = SpringApplicationContext.getClass(Class.forName(name));
                Method method = SiteUtil.getMethod(obj, schedingVO.getMethod(), SiteUtil.getStringForJSON(schedingVO.getParameters()));
                if(method == null){
                    throw new RuntimeException(obj.getClass().getName()+"中不存在"+schedingVO.getMethod()+"方法");
                }
                return new LocalRequestRpc(method,obj,schedingVO);
            } catch (ClassNotFoundException e) {
                logger.error("构建失败：",e);
            }
        }else{
            throw new RuntimeException("协议暂不支持...");
        }
        return null;
    }
}
